﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Core.Model;
using Core.Services;
using Infrastructure.Repositories;
using UI.Infrastructure.Pictures;
using UI.Models.Catalog;
using Category = Core.Model.Category;

namespace UI.Controllers
{
    public class CatalogController : Controller
    {
        private readonly ICatalogService _catalogService;
        private readonly IPictureRepository _pictureRepository;

        public CatalogController()
            : this(new CatalogService(new CatalogRepository()), new PictureRepository())
        {
        }

        public CatalogController(ICatalogService catalogService, IPictureRepository pictureRepository)
        {
            if (catalogService == null) throw new ArgumentNullException("catalogService");
            if (pictureRepository == null) throw new ArgumentNullException("pictureRepository");
            _catalogService = catalogService;
            _pictureRepository = pictureRepository;
        }
         [AllowAnonymous]
        public ActionResult ProductsPerCategory(string categoryId)
        {
            if (categoryId == null) return RedirectToAction("Index", "Home");

            Category category = _catalogService.GetCategory(categoryId);

            List<Product> products = _catalogService.GetProductsByCategory(categoryId);

            ProductsPerCategoryViewModel viewModel = new ProductsPerCategoryViewModelfactory().CreateFrom(products,
                                                                                                          category);

            return View("ProductsPerCategory", viewModel);
        }
         [AllowAnonymous]
        public ActionResult ItemDetails(string itemId)
        {
            if (itemId == null) return RedirectToAction("Index", "Home");

            Item item = _catalogService.GetItemDetails(itemId);

            string pictureFilePath = _pictureRepository.GetPictureFileNameForProduct(item.Product.ProductId);

            ItemDetailsViewModel viewModel = new ItemDetailsViewModelFactory().CreateFrom(item, pictureFilePath);

            return View("ItemDetails", viewModel);
        }

         [AllowAnonymous]
        public ActionResult ItemsPerProduct(string productId)
        {
            if (productId == null) return RedirectToAction("Index", "Home");

            Product product = _catalogService.GetProduct(productId);

            List<Item> items = _catalogService.GetItemsPerProduct(productId);

            ItemsPerProductViewModel viewModel = new ItemsPerProductViewModelFactory().CreateFrom(items, product);

            return View("ItemsPerProduct", viewModel);
        }
         [AllowAnonymous]
        public ActionResult ItemNotFound()
        {
            return View("ItemNotFound");
        }
    }
}